package com.sky.controller.user;

import com.sky.Service.DishService;
import com.sky.result.Result;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@Api(tags = "用户端-菜品接口")
@RestController(value = "userDishController")
@RequestMapping("/user/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("根据id查询菜品列表")
    @GetMapping("/list")
    public Result<List<DishVO>> getDishesListById(Long categoryId) {
        //构造redis中缓存的key
        String key = "dish_" + categoryId;
        //查询redis中是否有菜品数据
        List<DishVO> dishVOS = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if (dishVOS != null && dishVOS.size() > 0) {
            //如果存在，直接返回，无需查询数据库
            return Result.success(dishVOS);
        }
        //如果不存在，则查询数据库，并将查询到的数据存入redis
        System.out.println("categoryId:" + categoryId);
        dishVOS = dishService.getDishListById(categoryId);
        //存入redis
        redisTemplate.opsForValue().set(key,dishVOS);
        return Result.success(dishVOS);
    }
}
